import DGToast from "../../../../components/DGToast.tsx";
import DGDialogLayout from "../../../../components/DGDialogLayout/DGDialogLayout.tsx";
import DGDrawerLayout from "../../../../components/DGDrawerLayout/DGDrawerLayout.tsx";
import DGTextView from "../../../../components/DGTextView.tsx";
import {Util} from "../../../../sources/Util.ts";
import LoadingButton from "@mui/lab/LoadingButton";
import {TextField} from "@mui/material";
import DGConnect from "../../../../sources/DGConnect.ts";
import {ChangeEventHandler, FC, useState} from "react";
import {useNavigate} from "react-router-dom";
import {AlertColor} from "@mui/material/Alert/Alert";

interface DGToastProps {
    state: boolean,
    severity: AlertColor,
    text: string
}

interface SelfFormFreezeCodeProps {
    state: boolean,
    switchView: (text: string) => void,
}

const SelfFormFreezeCode: FC<SelfFormFreezeCodeProps> = ({state, switchView}) => {
    // 路由跳转
    const router = useNavigate();
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 验证码信息
    const [code, setCode] = useState("");
    // 发送状态
    const [sending, setSending] = useState(false);
    // 验证码错误信息
    const [error, setError] = useState({state: false, text: ""});
    // Toast 弹窗
    const [toast, setToast] = useState<DGToastProps>({state: false, severity: "info", text: ""});

    // 关闭控制
    const handleClose = () => {
        // 关闭
        switchView("");
        // 后退
        router(-1);
    }

    // 设置验证码信息
    const handleChangeCode: ChangeEventHandler<HTMLInputElement> = (e) => {
        // 清空错误信息
        setError({state: false, text: ""});
        // 设置账号信息
        setCode(e.target.value);
    }

    // 重发验证码
    const handleSendCode = () => {
        // 开始加载
        setSending(true);
        // 发起获取验证码请求
        DGConnect.POST(JSON.stringify({type: "freeze", getCode: 1}), result => {
            // 关闭加载
            setSending(false);
            // 设置错误信息
            if (result["data"]["code"] !== 200) return setError({
                state: true, text: result["data"]["message"] + "错误码：" + result["data"]["code"]
            });
            // 显示邮件发送成功
            setToast({state: true, severity: "success", text: "邮件发送成功！"});
        }, error => {
            // 关闭加载
            setSending(false);
            // 设置错误信息
            setToast({state: true, severity: "error", text: "发送失败！出现了错误：" + error["stack"]});
        });
    }


    // 提交函数
    const handleSubmit = () => {
        // 清空错误信息
        setError({state: false, text: ""});
        // 判断验证码是否为空
        if (code === "") return setError({state: true, text: "验证码输入不能为空！"});
        // 开始加载
        setLoading(true);
        // 发起请求
        DGConnect.POST(JSON.stringify({type: "freeze", code: code}), result => {
            // 关闭加载
            setLoading(false);
            // 错误信息
            if (result["data"]["code"] !== 200) return setError({
                state: true, text: result["data"]["message"] + "错误码：" + result["data"]["code"]
            });
            // 删除验证邮箱信息
            Util.Storage.delSession("FREEZE-EMAIL");
            // 成功跳转
            switchView("freeze_result");
        }, error => {
            // 关闭加载
            setLoading(false);
            // 设置错误信息
            setError({state: true, text: "遇到了一些问题，请尝试重试，或者及时联系我们！错误信息：" + error["stack"]});
        });
    }


    // DOM 节点
    const ContentView = (<>
        {/* 显示提示语 */}
        <DGTextView Body Bold color="error">
            注意：请不要频繁获取验证码，会导致邮箱被我们锁定 168 小时。如您的邮箱被我们锁定，请前往安全中心提交材料进行解除。
        </DGTextView>
        {/* 提示语 */}
        <DGTextView Body Bold>
            验证码已发送至您账户绑定的邮箱【{Util.Storage.getSession("FREEZE-EMAIL")}】，请检查您的收件箱。
            如未收到邮件，请检查垃圾邮件文件夹，或点击 （
            <LoadingButton disabled={loading ? loading : sending} loading={sending} onClick={() => handleSendCode()}>
                重发
            </LoadingButton>
            ） 验证码。
        </DGTextView>
        {/* 账号输入框 */}
        <TextField
            margin="dense" label="请输入验证码" variant="standard" type="number" disabled={loading}
            value={code} onChange={handleChangeCode} error={error.state} helperText={error.text} fullWidth required/>
    </>);

    return (<>
        <DGToast state={toast} close={() => setToast({state: false, severity: toast.severity, text: toast.text})}/>
        {/* DGDialogLayout 样式 */}
        <DGDialogLayout
            submit={{name: "继续", click: () => handleSubmit()}}
            back={{name: "返回", click: () => switchView("freeze_index")}}
            title="自助冻结" state={state} close={() => handleClose()} load={loading} PANEL AUTO>
            {ContentView}
        </DGDialogLayout>
        {/*DGDrawerLayout 样式 */}
        <DGDrawerLayout
            submit={{name: "继续", click: () => handleSubmit()}}
            more={{name: "返回", click: () => switchView("freeze_index")}}
            title="自助冻结" state={state} close={() => handleClose()} flex="bottom" load={loading} PANEL AUTO>
            {ContentView}
        </DGDrawerLayout>
    </>);
}
export default SelfFormFreezeCode;